package com.wpf.handlers;

import com.wpf.beans.MethodInfo;
import com.wpf.beans.ServerInfo;
import com.wpf.interfaces.RestHandler;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public class FluxClientRestHandler implements RestHandler {
    private WebClient webClient;
    @Override
    public void init(ServerInfo serverInfo) {
        // 通过使用  Webclient 创建 client, 之后所有的请求都用这个client发送请求
        this.webClient = WebClient.create(serverInfo.getUrl());
    }

    @Override
    public Object invokeRest(MethodInfo methodInfo) {
        Object object;
        WebClient.ResponseSpec retrieve = null;
        WebClient.RequestBodySpec request = this.webClient
                // 创建请求方法
                .method(methodInfo.getMethod())
                //  创建请求参数
                .uri(methodInfo.getUrl(), methodInfo.getParams())
                // 创建请求类型
                .accept(MediaType.APPLICATION_JSON);

        if(methodInfo.getBody() != null){
            // 发送请求
             retrieve = request.body(methodInfo.getBody(), methodInfo.getBodyType()).retrieve();
        }else {
            retrieve = request.retrieve();
        }

        // 判断异常
        retrieve.onStatus(status-> status.value() == 404,
                response-> Mono.just(new RuntimeException("Not Found!"))
                );


        // 创建请求body
        if(methodInfo.isReturnFlux()){
            object = retrieve.bodyToFlux(methodInfo.getReturnElementType());
        }else {
            object = retrieve.bodyToMono(methodInfo.getReturnElementType());
        }
        return object;
    }
}
